//
//  AppDelegate.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 20-02-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "AppDelegate.h"
#import "Reachability.h"
#import "Flurry.h"
#import <FacebookSDK/FacebookSDK.h>
#import <Parse/Parse.h>

@implementation AppDelegate

#define kVERSION @"version"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    //Test Test2 Test3

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    // saving an NSString
    [prefs setObject:@"LoadHomeFirst" forKey:@"keyToLookupString"];

    [prefs setObject:@"" forKey:@"StringSearch"];

    [prefs setObject:@"" forKey:@"strEmailCurrentUser"];

    [prefs setObject:@"1" forKey:@"strCurrentTypeOfLogin"];           //1: Login normal, 2: Login desde el área personal

    [prefs setObject:@"0" forKey:@"strIdDepartment"];                 //Identifica el Id de departamento si la búsqueda es por este concepto

    [prefs setObject:@"0" forKey:@"strNroInvoiceSelected"];           //Identifica el Id de departamento si la búsqueda es por este concepto
    
    [prefs setObject:@"Sin especificar" forKey:@"strFechaEntrega"];   //Define la fecha de entrega a asignar en la orden cada vez que se va a realizar una transacción, se limpia al presionar "Pagar".

    [prefs setObject:@"" forKey:@"strFechaEntregaDescription"];       //Almacena la fecha en formato "2014/11/24 Miércoles"
    
    // use this for highlighted color
/*
    [[UITabBar appearance] setSelectedImageTintColor:[UIColor colorWithRed:(256/256.0) green:(0/256.0) blue:(0/256.0) alpha:(1.0)]];
    
    // Use this to channge the tint colo of the entere TabBar
    [[UITabBar appearance] setTintColor:[UIColor colorWithRed:(255/256.0) green:(0/256.0) blue:(0/256.0) alpha:(1.0)]];
    
    // This change only a background color
    [[UITabBar appearance] setBackgroundColor:[UIColor colorWithRed:(255/256.0) green:(255/256.0) blue:(255/256.0) alpha:1.0]];

    [[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageNamed:@"YourIMG.png"]];
 */
    
    [[UITabBar appearance] setTintColor:[UIColor colorWithRed:(113/256.0) green:(195/256.0) blue:(97/256.0) alpha:(1.0)]];

    // Initialize Reachability
    Reachability *reachability = [Reachability reachabilityWithHostname:@"www.google.com"];
    
    reachability.reachableBlock = ^(Reachability *reachability) {
        NSLog(@"Network is reachable.");
    };
    
    reachability.unreachableBlock = ^(Reachability *reachability) {
        NSLog(@"Network is unreachable.");
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"No existe conexión a internet, intente nuevamente."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    };
    
    // Start Monitoring
    [reachability startNotifier];
    
//-----------------------------------------------------------------------------------------------------------------------------------------------
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    UITabBar *tabBar = tabBarController.tabBar;
    UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
    UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
    UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
    UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];
    UITabBarItem *tabBarItem5 = [tabBar.items objectAtIndex:4];
    
    tabBarItem1.selectedImage = [[UIImage imageNamed:@"icon_inicio_activo.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.image = [[UIImage imageNamed:@"icon_inicio.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.title = @"Inicio";
    
    tabBarItem2.selectedImage = [[UIImage imageNamed:@"icon_buscar_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.image = [[UIImage imageNamed:@"icon_buscar.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.title = @"Buscar";
    
    tabBarItem3.selectedImage = [[UIImage imageNamed:@"icon_carro_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.image = [[UIImage imageNamed:@"icon_carro.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.title = @"Carro";
    
    tabBarItem4.selectedImage = [[UIImage imageNamed:@"icon_cuenta_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.image = [[UIImage imageNamed:@"icon_cuenta.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.title = @"Cuenta";

    tabBarItem5.selectedImage = [[UIImage imageNamed:@"icon_chat_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.image = [[UIImage imageNamed:@"icon_chat.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.title = @"Chat";
    
//-----------------------------------------------------------------------------------------------------------------------------------------------
    
    [Flurry startSession:@"DS5BSJB3HG9QQSFXZ2GW"];
    //your code

//Verificamos si es una actualización de software para cambiar la versión de base de datos local de la App instalada
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bundleVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    if ([userDefaults objectForKey:kVERSION]) {
        NSString *version = [userDefaults objectForKey:kVERSION];
        if (![version isEqualToString:bundleVersion]) {
            [self replaceDatabase];
            [userDefaults setObject:bundleVersion forKey:kVERSION];
        }
    } else {
        [self replaceDatabase];
        [userDefaults setObject:bundleVersion forKey:kVERSION];
    }
    
// Override point for customization after application launch.
    [FBLoginView class];

//Configuración de Parse.com y notificaciones remotas
//-----------------------------------------------------------------------------------------------------------------------------------------------
    [Parse setApplicationId:@"ZhuaTG1XQ78aDbF8Hoxxqn56jCfuDVwrVyzBqN7s"
                  clientKey:@"gIeQFWn0Y3hzSY0JMz4EuL8eLSZUGw1NaHVlOsPm"];
    
    // Register for Push Notitications
    UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert |
                                                    UIUserNotificationTypeBadge |
                                                    UIUserNotificationTypeSound);
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes
                                                                             categories:nil];
    [application registerUserNotificationSettings:settings];
    [application registerForRemoteNotifications];
//-----------------------------------------------------------------------------------------------------------------------------------------------
    
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Store the deviceToken in the current installation and save it to Parse.
    PFInstallation *currentInstallation = [PFInstallation currentInstallation];
    [currentInstallation setDeviceTokenFromData:deviceToken];
    currentInstallation.channels = @[ @"global" ];
    [currentInstallation saveInBackground];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [PFPush handlePush:userInfo];
}

- (void)replaceDatabase
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // remove old sqlite database from documents directory
    NSURL *dbDocumentsURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"ecommerce.sqlite"];
    NSString *dbDocumentsPath = [dbDocumentsURL path];
    if ([fileManager fileExistsAtPath:dbDocumentsPath]) {
        NSError *error = nil;
        [fileManager removeItemAtPath:dbDocumentsPath error:&error];
        if (error) {
            NSLog(@"Error deleting sqlite database: %@", [error localizedDescription]);
        }
    }
    
    // move new sqlite database from bundle to documents directory
    NSString *dbBundlePath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"sqlite"];
    if (dbBundlePath) {
        NSError *error = nil;
        [fileManager copyItemAtPath:dbBundlePath toPath:dbDocumentsPath error:&error];
        if (error) {
            NSLog(@"Error copying sqlite database: %@", [error localizedDescription]);
        }
    }
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    // Call FBAppCall's handleOpenURL:sourceApplication to handle Facebook app responses
    BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
    
    // You can add your app-specific url handling code here if needed
    
    return wasHandled;
}

- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
